/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 #include <hi_types_base.h>
 #include <stdio.h>
 #include <unistd.h>
 #include "ohos_init.h"
 #include "iot_pwm.h"
 #include "iot_gpio.h"
 #include "hi_io.h"
 
 #define SERVO_PWM_PORT 0  // PWM端口号
 #define SERVO_PWM_FREQ 50 // 舵机PWM频率（50Hz）
 #define SERVO_MIN_PULSE 500  // 0度对应的脉宽（0.5ms，单位：微秒）
 #define SERVO_MAX_PULSE 2500 // 180度对应的脉宽（2.5ms，单位：微秒）
 
 // 设置舵机角度
 void SetServoAngle(int angle)
 {
    
    if (angle < 0) angle = 0;
    if (angle > 180) angle = 180;

    // 计算脉宽（占空比）
    int pulseWidth = SERVO_MIN_PULSE + (angle * (SERVO_MAX_PULSE - SERVO_MIN_PULSE)) / 180;
    
    //IoTGpioSetOutputVal(HI_IO_FUNC_GPIO_0_JTAG_TDO,1);
    //usleep(pulseWidth);
    //IoTGpioSetOutputVal(HI_IO_FUNC_GPIO_0_JTAG_TDO,0);
    //usleep(20000-pulseWidth);
    IoTPwmStart(3,pulseWidth,80000);
    usleep(20000);
    IoTPwmStop(3);
 }
 
 int qidong(void)
 {
    IoTGpioInit(HI_IO_FUNC_GPIO_0_JTAG_TDO);
    printf("init success \n");
    hi_io_set_func(HI_IO_FUNC_GPIO_0_JTAG_TDO,HI_IO_FUNC_GPIO_0_PWM3_OUT);
    printf("fuck! success \n");
    IoTGpioSetDir(HI_IO_FUNC_GPIO_0_JTAG_TDO,1);
    printf("setdir ok \n");
    IoTPwmInit(3);
    
     // 控制舵机从0度到180度旋转
     for (int angle = 0; angle <= 180; angle += 10) {
        SetServoAngle(angle);
        printf("Setting servo angle to %d degrees\n", angle);
        usleep(500000); // 等待 500ms
    }
 
     // 控制舵机从180度回到0度
     for (int angle = 180; angle >= 0; angle -= 10) {
        SetServoAngle(angle);
        printf("Setting servo angle to %d degrees\n", angle);
        usleep(500000); // 等待 500ms
    }
    
     return 0;
 }

SYS_RUN(qidong);
